package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.RestBloomFilter;
import com.atguigu.gmall.product.service.SkuInfoService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class RestBloomFilterImpl implements RestBloomFilter {

    @Autowired
    private RedissonClient redissonClient ;

    @Autowired
    private SkuInfoService skuInfoService ;

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @Override
    public void resetBloomFilter() {

        // 创建一个新的布隆过滤器(skuId-bloom-filter-new)
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("skuIds-bloom-filter-new");
        bloomFilter.tryInit(100000 , 0.00001) ;
        List<Long> skuIds = skuInfoService.findAllSkuIds();
        skuIds.forEach(skuId -> {
            bloomFilter.add(skuId) ;
        });
        bloomFilter.add(100L) ;             // 为了和之前的布隆过滤器区分

        // 删除之前的布隆过滤器(skuId-bloom-filter)，对新的布隆过滤器进行重命名
        String script = "redis.call('del' , KEYS[1])\n" +
                "redis.call('del' , \"{\"..KEYS[1]..\"}:config\")\n" +
                "redis.call('rename' , KEYS[2] , KEYS[1])\n" +
                "redis.call('rename' , \"{\"..KEYS[2]..\"}:config\" , \"{\"..KEYS[1]..\"}:config\")\n" +
                "return 1 " ;

        // 执行lua脚本
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList("skuIds-bloom-filter", "skuIds-bloom-filter-new"));
        if(result == 1) {
            log.info("布隆过滤器重置成功....");
        }

    }

}
